import { Injectable, HttpException } from '@nestjs/common'
import CaptchaClient, { VerifyIntelligentCaptchaRequest } from '@alicloud/captcha20230305'
import Credential from '@alicloud/credentials'
import ossConfig from '@/config/oss'

interface AliCaptchaResponseBody {
  success: boolean;
  code: string;
  message: string;
  [key: string]: any;
}

@Injectable()
export class CaptchaService {
  private client: CaptchaClient

  constructor() {
    this.client = this.createClient()
  }

  private createClient(): CaptchaClient {
    const credential = new Credential({
      type: 'access_key',
      accessKeyId: ossConfig.accessKeyId as string,
      accessKeySecret: ossConfig.accessKeySecret as string
    } as any)

    const config = {
      credential: credential,
      endpoint: 'captcha.cn-shanghai.aliyuncs.com',
      regionId: 'cn-shanghai'
    } as any

    return new CaptchaClient(config)
  }

  async verifyIntelligentCaptcha(captchaVerifyParam: string): Promise<boolean> {
    try {
      // 创建VerifyIntelligentCaptchaRequest实例
      const request = new VerifyIntelligentCaptchaRequest({
        captchaVerifyParam: captchaVerifyParam,
        sceneId: '7xzaxqkx'
      } as any)

      const response = await this.client.verifyIntelligentCaptchaWithOptions(request, {} as any)

      const responseBody = response.body as unknown as AliCaptchaResponseBody | undefined
      if (!responseBody) {
        throw new HttpException('验证码校验无响应数据', 500)
      }

      const { success, code, message } = responseBody

      if (success) {
        return true
      } else {
        console.error(`验证码校验失败: code=${code}, message=${message}`)
        return false
      }
    } catch (error) {
      console.error('阿里云API调用异常:', error.message)
      return false
    }
  }
}
